package org.dslintegration.merge;

import org.dslintegration.merge.core.MergeContext;
import org.dslintegration.merge.km3.core.Attribute;
import org.dslintegration.merge.km3.core.Class;
import org.dslintegration.merge.km3.core.ModelElement;
import org.dslintegration.merge.km3.core.Package;
import org.dslintegration.merge.km3.core.StructuralFeature;

//TODO: Migrate to MergeContext
public class KM3MetamodelUtils {
	public static Package findPackage(String qualifiedName, MergeContext context, boolean create) {
		for (Package p : context.getMetamodel().getContents()) {
			if (p.getName().compareToIgnoreCase(qualifiedName) == 0) {
				return p;
			}
		}
		if (create) {
			Package pack = new Package();
			pack.setName(qualifiedName.substring(0, 1).toUpperCase() + qualifiedName.substring(1));
			context.add(pack);
			return pack;
		}
		return null;
	}

	public static Class findClass(String qualifiedName, MergeContext context, boolean create) {
		if (qualifiedName.split("\\.") == null || qualifiedName.split("\\.").length != 2)
			return null;
		String pack = qualifiedName.split("\\.")[0];
		String claz = qualifiedName.split("\\.")[1];
		for (Package p : context.getMetamodel().getContents()) {
			if (p.getName().compareToIgnoreCase(pack) == 0) {
				for (ModelElement me : p.getContents()) {
					if (me instanceof Class && me.getName().equals(claz)) {
						return (Class) me;
					}
				}
			}
		}
		if (create) {
			Package newPack = KM3MetamodelUtils.findPackage(pack, context, true);
			Class newClazz = new Class();
			newClazz.setName(claz);
			newClazz.setParent(newPack);
			context.add(newClazz);
			return newClazz;
		}
		return null;
	}

	public static Attribute findAttribute(Class clazz, String name) {
		for (StructuralFeature f : clazz.getStructuralFeatures()) {
			if (f instanceof Attribute && f.getName().equals(name)) {
				return (Attribute) f;
			}
		}
		return null;
	}
}
